package com.sfzd5.aiclassroom;

import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Collections;

public class WsServer extends WebSocketServer {
    private static int counter = 0;
    private static int port = 9002;

    public static String WsServerAddress() throws UnknownHostException {
        InetAddress addr = InetAddress.getLocalHost();
        return "ws://" + addr.getHostAddress() + ":" + port;
    }

    public WsServer() throws UnknownHostException {
        super(new InetSocketAddress(port), Collections.singletonList(new Draft_6455()));
        this.setConnectionLostTimeout(0);
    }

    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
        System.out.println("客户端连接");
    }

    @Override
    public void onClose(WebSocket webSocket, int i, String s, boolean b) {

    }

    @Override
    public void onMessage(WebSocket webSocket, String s) {
        if(s.equals("exit")){
            try {
                this.stop();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("服务端收到消息：" + s);
            webSocket.send("返回消息->" + s);
        }

    }

    @Override
    public void onError(WebSocket webSocket, Exception e) {

    }

    @Override
    public void onStart() {
        System.out.println("WebSocket Server started!");
    }
}
